package main;

import gui.LoginPanel;
import gui.MainPanel;
import gui.toolpanels.CNode;
import guiobj.CluPanelController;

import java.net.URI;
import java.util.LinkedList;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import utils.Msg;
import utils.SSHUtils;
import utils.Utils;
import data.UserInfo;
import data.WebSocket;
import jsonobj.ClusterIDInfo;
import jsonobj.JobInfo;
import jsonobj.LoginInfo;
import jsonobj.RegisterInfo;
import jsonobj.Response;

public class ClientFunctions implements Msg {
	
	public static boolean Register(RegisterInfo ri) throws Exception
	{
		if(Utils.ws == null)
		{
			Utils.ws = new WebSocket(new URI(Utils.server));
			Utils.ws.connect();
		}
		Utils.ws.send(ri);
		String recv = Utils.ws.recv();
		Response resp = Response.fromJSon(recv);
		if(!resp.success)
			Utils.out(resp.err);
		return resp.success;
	}
	
	public static byte Login(LoginInfo li) throws Exception
	{
		Utils.username = li.user;
		Utils.passwd = li.pass; //li.pass
		LoginPanel.jcomp8.setText("Connecting");

		if(Utils.ws == null)
		{
			Utils.ws = new WebSocket(new URI(Utils.server));
			Utils.ws.connect();
		}
		
		LoginPanel.jcomp8.setText("Sending login details");
		
		Utils.ws.send(li);
		String recv = Utils.ws.recv();
		Response r = Response.fromJSon(recv);
		Utils.out(r);
		if(!r.success) return r.err;
		String ss = Utils.ws.recv();
		Utils.out(ss);
		String s[] = ss.split("//|");
		//Utils.out(s[0]);Utils.out(s[1]);
		LinkedList<ClusterIDInfo> cid = null;
		cid = new Gson().fromJson(ss, new TypeToken<LinkedList<ClusterIDInfo>>() {}.getType());
		//Utils.out(cid.get(0).hostname);
		LinkedList<JobInfo> ji = null;
		//ji = new Gson().fromJson(s[1], new TypeToken<ArrayList<JobInfo>>() {}.getType());
		Utils.ui = new UserInfo(cid,ji);
		
		LoginPanel.jcomp8.setText("Connecting to file server");
		if(!SSHUtils.init(Utils.username, null))
		{
			LoginPanel.jcomp8.setText("Cannot connect to file server");
			Utils.ws.close();
			System.exit(0);
		}

		Utils.root = new CNode(Utils.username);
		LoginPanel.jcomp8.setText("Retreiving files information...");
		SSHUtils.buildFileSystem("~/", Utils.root);
		java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
            	Utils.p = new MainPanel();
            	Utils.p.setSize(1022,583);
            	Utils.p.splitPane.setDividerLocation(132);
            	Utils.p.setVisible(true);
            	Utils.p.jLabel1.setText("User: "+Utils.username);
            	Utils.p.jLabel2.setText("Disk Usage: Low");
            	Utils.p.jLabel3.setText("Total jobs running: 0");
            	if(!Utils.ui.cinfo.isEmpty())
            		Utils.p.cluCombo.removeAllItems();
            	for(ClusterIDInfo i : Utils.ui.cinfo)
            	{
            		CluPanelController.addClusterInfo(Utils.p, i);
            		if(i.isOn) Utils.p.cluCombo.addItem(i.local_hostname);
            	}
            }
        });
		new ReceiveThread().start();
		return OK;
	}
}
